package cn.openea.perpartner.link.scheduledtasks;

import cn.hutool.core.convert.Convert;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.link.constant.CommonConstants;
import cn.openea.perpartner.link.web.service.IShareLinkConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 分享链接定时任务
 * @createTime 2023年05月22日 10:14:00
 */
@Slf4j
@Component
public class ShareLinkTask {

    @Resource
    private RedisCache redisCache;
    @Resource
    private IShareLinkConfigService shareLinkConfigService;

    /**
     * 同步链接点击量
     * 3小时执行一次
     */
    @Scheduled(cron = "0 0 0/3 * * ?")
    public void visitsNumSyncService() {
        try {
            log.info("visits num sync service task start execution");
            Set<String> visitsNumKeyList = redisCache.patternKey(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM + "*");
            if (visitsNumKeyList.isEmpty()) {
                return;
            }
            visitsNumKeyList.parallelStream().forEach(key -> {
                Integer visitsNum = redisCache.getNumber(key);
                if (Objects.isNull(visitsNum) || visitsNum <= 0) {
                    redisCache.deleteObject(key);
                    return;
                }
                Long id = Convert.toLong(key.substring(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM.length()));
                if (Objects.isNull(id)) {
                    redisCache.deleteObject(key);
                    return;
                }
                try {
                    shareLinkConfigService.updateVisitsNum(id, visitsNum);
                    redisCache.deleteObject(key);
                } catch (Exception e) {
                    throw e;
                }

            });
        } catch (Exception e) {
            log.error("visits num sync service task execution failed，failure reason {}", e.getMessage());
        }

    }
}
